package dataAccess;

import java.sql.*;
import java.util.*;

import dataAccess.Connector;
import dataAccess.DALException;
import dataAccess.PlayerDTO;

public class MySQLPlayerDAO implements PlayerDAO {

	public PlayerDTO getPlayer(int playerID) throws DALException {
		ResultSet rs = Connector
				.doQuery("SELECT * FROM Player WHERE Player_ID = " + playerID);
		try {
			if (!rs.first())
				throw new DALException("Spilleren " + playerID + " findes ikke");
			return new PlayerDTO(rs.getInt("Player_ID"), rs.getString("Name"),
					rs.getInt("Account"), rs.getInt("Jailcard"),
					rs.getInt("field"), rs.getInt("turnsInJail"));
		} catch (SQLException e) {
			throw new DALException(e);
		}
	}

	public List<PlayerDTO> getPlayerList() throws DALException {
		List<PlayerDTO> data = new ArrayList<PlayerDTO>();
		ResultSet rs = Connector.doQuery("SELECT * FROM Player");
		try {
			while (rs.next()) {
				data.add(new PlayerDTO(rs.getInt("Player_ID"), rs
						.getString("Name"), rs.getInt("Account"), rs
						.getInt("Jailcard"), rs.getInt("field"), rs
						.getInt("turnsInJail")));
			}
		} catch (SQLException e) {
			throw new DALException(e);
		}
		return data;
	}

	public void createPlayer(PlayerDTO player) throws DALException {
		Connector.doUpdate("INSERT INTO Player VALUES ("
				+ player.getPlayer_ID() + ", '" + player.getName() + "' , "
				+ player.getAccount() + " , " + player.getJailcard() + " , "
				+ player.getField() + " , " + player.getTurnsInJail() + ");");
	}

	public void updatePlayer(PlayerDTO player) throws DALException {
		Connector.doUpdate("UPDATE Player SET Name = '" + player.getName()
				+ "', Account =" + player.getAccount() + " , Jailcard = "
				+ player.getJailcard() + " , field = " + player.getField()
				+ " , turnsInJail = " + player.getTurnsInJail()
				+ " WHERE Player_ID = " + player.getPlayer_ID() + ";");
	}

	public void deletePlayer(int playerID) throws DALException {
		Connector.doUpdate("DELETE FROM Player WHERE Player_ID = " + playerID);
	}

	public int getJailCards() throws DALException {

		ResultSet rs = Connector.doQuery("SELECT SUM(Jailcard) FROM Player");
		int i = 0;
		try {
			while (rs.next()) {
				i = rs.getInt(1);
				
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return i;
	}

}
